#include "../include/main_customer.hh"
#include "../include/main_account.hh"
#include "../include/main_utils.hh"
#include "../include/main_core.hh"
#include <algorithm>

// 处理客户注册
void handleCustomerRegistration(BankSystem& bankSystem, UIManager& uiManager) {
    clearScreen();
    
    std::string title;
    if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
        title = "===== Register New Customer =====";
    } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
        title = "===== Enregistrer un nouveau client =====";
    } else {
        title = "===== 注册新客户 =====";
    }
    
    std::cout << title << std::endl << std::endl;
    
    std::string promptName, promptPassword, promptConfirmPassword;
    std::string errPassword, errPasswordMismatch, regFailed, pressEnter;
    
    if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
        promptName = "Please enter customer name: ";
        promptPassword = "Please set a 6-digit numeric password: ";
        promptConfirmPassword = "Please confirm password: ";
        errPassword = "Error: Password must be 6 digits! Please try again.";
        errPasswordMismatch = "Error: Passwords do not match! Please try again.";
        regFailed = "Customer registration failed.";
        pressEnter = "Press Enter to continue...";
    } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
        promptName = "Veuillez entrer le nom du client: ";
        promptPassword = "Veuillez définir un mot de passe numérique à 6 chiffres: ";
        promptConfirmPassword = "Veuillez confirmer le mot de passe: ";
        errPassword = "Erreur: Le mot de passe doit comporter 6 chiffres! Veuillez réessayer.";
        errPasswordMismatch = "Erreur: Les mots de passe ne correspondent pas! Veuillez réessayer.";
        regFailed = "L'enregistrement du client a échoué.";
        pressEnter = "Appuyez sur Entrée pour continuer...";
    } else {
        promptName = "请输入客户姓名: ";
        promptPassword = "请设置6位数字密码: ";
        promptConfirmPassword = "请再次输入密码确认: ";
        errPassword = "错误：密码必须为6位数字！请重新输入。";
        errPasswordMismatch = "错误：两次输入的密码不一致！请重新输入。";
        regFailed = "客户注册失败。";
        pressEnter = "按回车键继续...";
    }
    
    std::string name = uiManager.getInput(promptName);
    
    // 获取6位数密码
    std::string password;
    bool validPassword = false;
    while (!validPassword) {
        password = uiManager.getInput(promptPassword);
        if (password.length() != 6 || !std::all_of(password.begin(), password.end(), ::isdigit)) {
            std::cout << errPassword << std::endl;
            continue;
        }
        
        // 再次确认密码
        std::string confirmPassword = uiManager.getInput(promptConfirmPassword);
        if (password != confirmPassword) {
            std::cout << errPasswordMismatch << std::endl;
            continue;
        }
        
        validPassword = true;
    }
    
    std::string regSuccess, rememberPassword;
    
    if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
        regSuccess = "Customer " + name + " registered successfully!";
        rememberPassword = "Please remember your password, it will be used for account operations and transaction confirmations.";
    } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
        regSuccess = "Client " + name + " enregistré avec succès!";
        rememberPassword = "Veuillez vous souvenir de votre mot de passe, il sera utilisé pour les opérations de compte et les confirmations de transaction.";
    } else {
        regSuccess = "客户 " + name + " 注册成功！";
        rememberPassword = "请记住您的密码，它将用于账户操作和交易确认。";
    }
    
    if (bankSystem.registerCustomer(name, password)) {
        std::cout << regSuccess << std::endl;
        std::cout << rememberPassword << std::endl;
    } else {
        std::cout << regFailed << std::endl;
    }
    
    std::cout << std::endl;
    uiManager.getInput(pressEnter);
}

// 处理客户账户访问
void handleCustomerAccess(BankSystem& bankSystem, UIManager& uiManager, AuthManager& authManager) {
    clearScreen();
    
    std::string title, errorNeedLogin, errorCustomerNotExist, pressEnter;
    
    if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
        title = "===== Access Customer Account =====";
        errorNeedLogin = "Error: You need to login first.";
        errorCustomerNotExist = "Error: Customer ";
        pressEnter = "Press Enter to continue...";
    } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
        title = "===== Accéder au compte client =====";
        errorNeedLogin = "Erreur: Vous devez vous connecter d'abord.";
        errorCustomerNotExist = "Erreur: Client ";
        pressEnter = "Appuyez sur Entrée pour continuer...";
    } else {
        title = "===== 访问客户账户 =====";
        errorNeedLogin = "错误：您需要先登录。";
        errorCustomerNotExist = "错误：客户 ";
        pressEnter = "按回车键继续...";
    }
    
    std::cout << title << std::endl << std::endl;
    
    // 获取当前登录用户
    auto currentUser = authManager.getCurrentUser();
    if (!currentUser) {
        std::cout << errorNeedLogin << std::endl;
        uiManager.getInput(pressEnter);
        return;
    }
    
    // 强制客户只能访问自己的账户
    std::string name = currentUser->getUsername();
    
    std::string accessingMessage;
    if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
        accessingMessage = "Accessing customer account: " + name;
    } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
        accessingMessage = "Accès au compte client: " + name;
    } else {
        accessingMessage = "正在访问客户账户: " + name;
    }
    
    std::cout << accessingMessage << std::endl;
    
    auto customer = bankSystem.findCustomerByName(name);
    
    if (!customer) {
        std::cout << errorCustomerNotExist << name << " not found." << std::endl;
        uiManager.getInput(pressEnter);
        return;
    }
    
    // 显示客户账户菜单
    while (true) {
        clearScreen();
        uiManager.showCustomerAccountsMenu(name);
        
        int choice = uiManager.getMenuChoice(1, 5);
        
        if (choice == 5) { // 返回主菜单
            break;
        }
        
        // 处理选择
        switch (choice) {
            case 1: { // 访问储蓄账户
                auto account = customer->getSavingsAccount();
                if (account) {
                    handleAccountOperations(bankSystem, uiManager, account->getAccountId());
                } else {
                    std::string errorMessage;
                    if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
                        errorMessage = "Error: Savings account not found.";
                    } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
                        errorMessage = "Erreur: Compte d'épargne introuvable.";
                    } else {
                        errorMessage = "错误：找不到储蓄账户。";
                    }
                    std::cout << errorMessage << std::endl;
                    uiManager.getInput(pressEnter);
                }
                break;
            }
            case 2: { // 访问支票账户
                auto account = customer->getCheckingAccount();
                if (account) {
                    handleAccountOperations(bankSystem, uiManager, account->getAccountId());
                } else {
                    std::string errorMessage;
                    if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
                        errorMessage = "Error: Checking account not found.";
                    } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
                        errorMessage = "Erreur: Compte courant introuvable.";
                    } else {
                        errorMessage = "错误：找不到支票账户。";
                    }
                    std::cout << errorMessage << std::endl;
                    uiManager.getInput(pressEnter);
                }
                break;
            }
            case 3: { // 查看所有交易
                clearScreen();
                
                std::string transactionTitle;
                std::string noTransactions;
                
                if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
                    transactionTitle = "===== All transactions for " + name + " =====";
                    noTransactions = "This customer has no transaction records.";
                } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
                    transactionTitle = "===== Toutes les transactions pour " + name + " =====";
                    noTransactions = "Ce client n'a aucun enregistrement de transaction.";
                } else {
                    transactionTitle = "===== " + name + " 的所有交易 =====";
                    noTransactions = "该客户尚无交易记录。";
                }
                
                std::cout << transactionTitle << std::endl << std::endl;
                
                auto transactions = bankSystem.getTransactionsByCustomerName(name);
                if (transactions.empty()) {
                    std::cout << noTransactions << std::endl;
                } else {
                    for (const auto& transaction : transactions) {
                        transaction.display();
                    }
                }
                
                uiManager.getInput(pressEnter);
                break;
            }
            case 4: { // 生成客户报告
                std::string reportSuccess, reportFailed;
                
                if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
                    reportSuccess = "Customer report generated successfully!";
                    reportFailed = "Report generation failed.";
                } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
                    reportSuccess = "Rapport client généré avec succès!";
                    reportFailed = "La génération du rapport a échoué.";
                } else {
                    reportSuccess = "已成功生成客户报告！";
                    reportFailed = "生成报告失败。";
                }
                
                if (bankSystem.generateCustomerReport(name)) {
                    std::cout << reportSuccess << std::endl;
                } else {
                    std::cout << reportFailed << std::endl;
                }
                
                uiManager.getInput(pressEnter);
                break;
            }
        }
    }
}

// 处理交易报告
void handleTransactionReports(BankSystem& bankSystem, UIManager& uiManager) {
    while (true) {
        clearScreen();
        uiManager.showTransactionReportsMenu();
        
        int choice = uiManager.getMenuChoice(1, 4);
        
        if (choice == 4) { // 返回主菜单
            break;
        }
        
        // 处理选择
        switch (choice) {
            case 1: { // 生成全局交易报告
                if (bankSystem.generateGlobalTransactionReport()) {
                    std::cout << "已成功生成全局交易报告！" << std::endl;
                } else {
                    std::cout << "生成报告失败。" << std::endl;
                }
                
                uiManager.getInput("按回车键继续...");
                break;
            }
            case 2: { // 生成客户交易报告
                std::string customerName = uiManager.getInput("请输入客户姓名: ");
                if (bankSystem.generateCustomerReport(customerName)) {
                    std::cout << "已成功生成客户交易报告！" << std::endl;
                } else {
                    std::cout << "生成报告失败。" << std::endl;
                }
                
                uiManager.getInput("按回车键继续...");
                break;
            }
            case 3: { // 生成账户交易报告
                std::string accountId = uiManager.getInput("请输入账户ID: ");
                if (bankSystem.generateAccountReport(accountId)) {
                    std::cout << "已成功生成账户交易报告！" << std::endl;
                } else {
                    std::cout << "生成报告失败。" << std::endl;
                }
                
                uiManager.getInput("按回车键继续...");
                break;
            }
        }
    }
}

// 处理客户菜单选项
void handleCustomerMenu(BankSystem& bankSystem, UIManager& uiManager) {
    while (true) {
        clearScreen();
        uiManager.showCustomerMenu();
        
        char choice = uiManager.getKeyChoice("ABCD");
        
        if (choice == 'D') { // 退出
            break;
        }
        
        // 处理选择
        switch (choice) {
            case 'A': // 注册新客户
                handleCustomerRegistration(bankSystem, uiManager);
                break;
            case 'B': // 访问客户账户
                handleCustomerAccess(bankSystem, uiManager, authManager);
                break;
            case 'C': // 交易报告
                handleTransactionReports(bankSystem, uiManager);
                break;
        }
    }
} 